package com.znyj.servlet.service;

import com.znyj.servlet.dao.MerchantDao;
import com.znyj.servlet.entity.MerchantEntity;
import com.znyj.servlet.model.MerchantQueryModel;
import com.znyj.servlet.sqlHelper.Order;
import com.znyj.servlet.sqlHelper.SqlRequest;
import com.znyj.servlet.vo.Page;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by gaoliwei02 on 2017/9/20.
 */
@Service
public class MerchantService {
    private static final Logger logger = Logger.getLogger(MerchantService.class);

    @Autowired
    private MerchantDao merchantDao;

    public int insertMerchant(MerchantEntity merchantEntity) {
        return merchantDao.insert(merchantEntity);
    }

    public int updateMerchant(MerchantEntity merchantEntity) {
        return merchantDao.update(merchantEntity);
    }

    public MerchantEntity findByPoiid(int poiid) {
        return merchantDao.findByPoiid(poiid);
    }

    public List<MerchantEntity> findBindMerchant(String deviceId) {
        return merchantDao.findBindMerchant(deviceId);
    }

    public long findNewestPoiid() {
        return merchantDao.findNewestPoiid();
    }

    public Page<MerchantEntity> createMerchantPage(MerchantQueryModel merchantQueryModel) {
        int skip = merchantQueryModel.getOffset();
        SqlRequest sqlRequest = new SqlRequest("cdb_merchant", "*");

        if (merchantQueryModel.getBdName() == null || merchantQueryModel.getBdName().equals("")) {

        } else {
            sqlRequest.EQ("bd_name", merchantQueryModel.getBdName());
        }

        if (merchantQueryModel.getPoiid() == -1) {

        } else {
            sqlRequest.EQ("poiid", merchantQueryModel.getPoiid());
        }

        if (merchantQueryModel.getMerchantName() == null || merchantQueryModel.getMerchantName().equals("")) {

        } else {
            sqlRequest.EQ("merchant_name", merchantQueryModel.getMerchantName());
        }

        //sqlRequest.LT("create_time", taskQueryModel.getCreateTime());

        if (merchantQueryModel.getOrder().equals("asc")) {
            sqlRequest.addOrder("id", Order.Sort.ASC);
        } else {
            sqlRequest.addOrder("id", Order.Sort.DESC);
        }

        int count = merchantDao.count(sqlRequest);
        sqlRequest.Limit(skip, merchantQueryModel.getPageSize());
        if (merchantQueryModel.getPageSize() == -1) {
            return null;
        }

        List<MerchantEntity> cdbMerchantEntities = merchantDao.query(sqlRequest);

        Page<MerchantEntity> page = Page.createPage(merchantQueryModel.getPageNumber(), merchantQueryModel.getPageSize(), cdbMerchantEntities, count);
        return page;
    }
}
